package com.tungse.juc.product_consumers;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class PCDemo2 {

    public static void main(String[] args) {
        Data2 data = new Data2();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                data.printC();
            }
        },"C").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                data.printB();
            }
        },"B").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                data.printA();
            }
        },"A").start();


    }
}


//执行顺序   等待  业务  通知
class Data2 {//资源类
    Lock lock = new ReentrantLock();
    //Condition 能够做到精准的通知
    Condition conditionA = lock.newCondition();
    Condition conditionB = lock.newCondition();
    Condition conditionC = lock.newCondition();

    private int num = 0;

    public void printA() {
        print("AAAAA", 0, 1, conditionA, conditionB);
    }

    public void printB() {
        print("BBBBB", 1, 2, conditionB, conditionC);
    }

    public void printC() {
        print("CCCCC", 2, 0, conditionC, conditionA);
    }
    private void print(String methodName, int currentNum, int nextNum, Condition current, Condition next) {
        lock.lock();
        try{
            while (num != currentNum) {
                current.await();
            }
            System.out.println(Thread.currentThread().getName() + "=>" + methodName);
            num = nextNum;
            next.signal();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }
}